package com.opal.stockTaking.service.Impl;

import com.opal.consts.CommonConst;
import com.opal.consts.WSC;
import com.opal.domain.R;
import com.opal.domain.ReturnMessageData;
import com.opal.model.DataGridData;
import com.opal.model.EasyUiTree;
import com.opal.stockTaking.entity.HSDSummary;
import com.opal.stockTaking.entity.HSDSummaryResultData;
import com.opal.stockTaking.mapper.oracle.HSDSummaryMapper;
import com.opal.stockTaking.service.HSDSummaryService;
import com.opal.system.entity.table.OpalUser;
import com.opal.system.entity.table.PKOrg;
import com.opal.utils.CommonUtils;
import com.opal.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class HSDSummaryServiceImpl implements HSDSummaryService {

    @Autowired
    private HSDSummaryMapper hsdSummaryMapper;
    @Override
    public Object getOrgService() {
        OpalUser sessionUser = UserUtils.getSessionUser();
        List<PKOrg> orgs = hsdSummaryMapper.getOrg();
        List<PKOrg> result= new ArrayList<>();
        if (sessionUser !=null){
            String[] userOrg = sessionUser.getHrorgPkhrorg().split(",");
            for(PKOrg org: orgs){
                int i=0;
               for (String uo:userOrg){
                   if (uo.equals(org.getPkOrg())){
                       i=1;
                       break;
                   }
               }
               if(i==1){
                   result.add(org);
               }
            }

        }
        return result;
    }

    @Override
    public List<EasyUiTree> getStordocService(String pkOrg) {
        List<Map<String, String>> result = hsdSummaryMapper.getStordoc(pkOrg);
        //封装到EasyUiTree中
        List<EasyUiTree> list= new ArrayList<>();
        EasyUiTree easyUiTree= new EasyUiTree("0","全部");
        easyUiTree.setState("open");
        list.add(easyUiTree);
        if(result.size()>0){
            for (Map<String,String> r:result){
                easyUiTree.getChildren().add(new EasyUiTree(r.get("CODE"),r.get("NAME"),"open"));
            }
        }
        return list;
    }

    @Override
    @Transactional(value = "oracleTransactionManager",rollbackFor = {Exception.class})
    public Object createDateService(HSDSummary hsdSummary) {
        OpalUser opalUser = UserUtils.getSessionUser();
        if (opalUser ==null){
            return new ReturnMessageData(WSC.PRECONDITIONFAILED,"账户已过期");
        }
        //判断传过来的数据
        String rStr = this.isHSDSummaryData(hsdSummary);
        if (rStr != null){
            return new ReturnMessageData(WSC.PRECONDITIONFAILED,rStr);
        }
        try {
            //1、根据仓库编码进行插入cx_stocno表：调用存储过程之前先要插入
            System.out.println("插入开始。。。"+System.currentTimeMillis());
           List<String> list=new ArrayList<>();

            for (String str :hsdSummary.getWarehouseCode()) {
                if(!"0".equals(str)){
                    list.add(str);
                    hsdSummaryMapper.insertStocno(str);
                }
            }
            System.out.println("调用存储过程开始。。。"+System.currentTimeMillis());
            //2、调存储过程：这里需要花费点时间
            hsdSummaryMapper.call(hsdSummary);
            log.info("用户【"+opalUser.getUserName()+"】:在【"+ CommonUtils.getCurrentDateTimeString()+"时间段操作【收发存汇总】模块的按钮【生成数据】成功生成了数据");

            //处理导出所有数据的按钮有时候是空的问题:把查询道的数据封装到本类静态成员变量中
            System.out.println("调用存储过程结束。。。开始查询数据"+System.currentTimeMillis());
            List<HSDSummaryResultData> hsdSummaryResultData = hsdSummaryMapper.queryAllDataMapper(hsdSummary.getUid(),list);
            CommonConst.hr.put(opalUser.getUserId(),hsdSummaryResultData);

        }catch (Exception e){
            e.printStackTrace();
            log.info("用户【"+opalUser.getUserName()+"】:在"+ CommonUtils.getCurrentDateTimeString()+"时间段操作【收发存汇总】模块的按钮【生成数据】出现异常如下："+e.getMessage());
            return new ReturnMessageData(WSC.REQUEST_ERROR,"处理数据失败！请稍后操作或联系管理员");
        }
        return new ReturnMessageData(WSC.RESTPONSE_OK,"数据生成成功，请点击【查看】按钮查看数据");
    }

    @Override
    public Object emptyDateService() {
        try {
            hsdSummaryMapper.deleteStocno();
            hsdSummaryMapper.deleteSumary();
            hsdSummaryMapper.deleteFlow();   //查询到调用封装在oracele的包中函数有进行先删除这两个表的操作
            hsdSummaryMapper.deleteFlow_b();
        }catch (Exception e){
            return new R(WSC.REQUEST_ERROR,"清空失败！请重新操作！");
        }
        return new R(WSC.RESTPONSE_OK,"已清空！请生成数据！");
    }

    @Override
    @Transactional(value = "oracleTransactionManager",rollbackFor = {Exception.class})
    public Object queryDataService(HSDSummary hsdSummary) {
        OpalUser opalUser = UserUtils.getSessionUser();
        if (opalUser ==null){
            return new ReturnMessageData(404,"账户已过期,请重新登录");
        }
        try {
            //分页
            int pageNumber = hsdSummary.getPage();
            int pageSize = hsdSummary.getRows();
            //总数
            Map<Long, Object> hr = CommonConst.hr;
            List<HSDSummaryResultData> data= (List<HSDSummaryResultData>) hr.get(opalUser.getUserId());
            int total=data.size();
            System.out.println(total+"----------------------");

            int fromIndex = pageSize * (pageNumber - 1);
            //判断 若大于或等于总数，直接总数
            int toIndex = pageNumber*pageSize;
            if (toIndex >= total) {
                toIndex = total;
            }
            //获取索引范围内数据：参数一：第一个索引，参数二：最后一个索引(包头不包尾)
            data=data.subList((pageNumber-1)*pageSize, toIndex);

            DataGridData d= new DataGridData();
            d.setTotal(total);
            d.setRows(data);
            log.info("用户【"+opalUser.getUserName()+"】:在"+ CommonUtils.getCurrentDateTimeString()+"时间段操作【收发存汇总】模块的按钮【查看】获取"+total+"条数据");
            return d;
        }catch (Exception e){
            e.printStackTrace();
            log.info("用户【"+opalUser.getUserName()+"】:在"+ CommonUtils.getCurrentDateTimeString()+"时间段操作【收发存汇总】模块的按钮【查看】获取数据出现异常如下："+e.getMessage());
          return  new ReturnMessageData(500,"服务器维护中...");
        }

    }

    @Override
    public List<HSDSummaryResultData> exportDataService() {
        //根据当前用户的id获取数据
        Map<Long, Object> hr = CommonConst.hr;

        return (List<HSDSummaryResultData>) hr.get(UserUtils.getSessionUserId());
    }

    public String isHSDSummaryData(HSDSummary hsdSummary){
        //时间
        try {
            SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
            Date start = s.parse(hsdSummary.getStartDate());
            Date end = s.parse(hsdSummary.getEndDate());
            if (start.getTime()>end.getTime()){
                return "开始日期不能大于结束日期";
            }
        }catch (Exception e){
            return "时间格式不对";
        }
        //组织
        if (hsdSummary.getWarehouseCode()==null){
            return "必须条件：仓库未选择!";
        }
        return null;
    }
}
